package traveldream.ejb.sessionBean;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import traveldream.ejb.DTO.ExcursionDTO;
import traveldream.ejb.entities.Excursion;
import traveldream.ejb.interfaces.ExcursionBeanLocal;
import traveldream.ejb.interfaces.NoDeleteException;
import traveldream.ejb.interfaces.NotFindException;

/**
 * Session Bean implementation class ExcursionBean
 */
@Stateless
public class ExcursionBean implements ExcursionBeanLocal {
	
	@PersistenceContext
	private EntityManager em;
    /**
     * Default constructor. 
     */
    public ExcursionBean() {
        // TODO Auto-generated constructor stub
    }
    
    public List<ExcursionDTO> getAllExcursion(){
    	List<Excursion> excursions = em.createNamedQuery(Excursion.FIND_ALL).getResultList();
    	List<ExcursionDTO> eDTO = new ArrayList<ExcursionDTO>();
    	
    	for(Excursion e : excursions){
    		eDTO.add(e.convertToDTO());
    	}
    	return eDTO;
    }
    
    public ExcursionDTO find(int id) throws NotFindException{
    	Excursion e = em.find(Excursion.class, id);
    	try{
    		return e.convertToDTO();
    	}
    	catch(NullPointerException ex){
    		throw new NotFindException();
    	}
 
    }

	@Override
	public void delete(int id) throws NotFindException,NoDeleteException{
		// TODO Auto-generated method stub
		Excursion e = em.find(Excursion.class, id);
    	try{
    		for(int i=0;i<e.getDefaultPackages().size();i++){
    			if(!e.getDefaultPackages().get(i).isInvalid())
    				throw new NoDeleteException();				
    		}
    		e.setInvalid(true);
    	}
    	catch(NullPointerException ex){
    		throw new NotFindException();
    	}
	}
	
}

